/*

Copyright (C) 2007 Thomas Geiger (tom.geiger@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

#ifndef OGSADAICONNECTION_H_
#define OGSADAICONNECTION_H_

#include <jni.h>
#include <stdio.h>
#include <string.h>

#include <iostream>
#include <string>

using namespace std;

/**
 * This class is the bridge between C++ and the Java implementation of 
 * OGSADAIClient. 
 * 
 * Once instantiated, a JVM is invoked using JNI, initializing the Java object. 
 * Each call is delegated to the corresponding OGSADAIClient method.
 */
class OGSADAIConnection
{
	public:
		/**
		 * Constructor method (singleton), as we'd only like to 
		 * have on JVM running behind.
		 */
		static OGSADAIConnection* GetConnection();		
		/**
		 * Dispose JVM
		 */
		virtual ~OGSADAIConnection();
		/**
		 * Open database connection.
		 * 
		 * Parameters:
		 * url	The url string to the OGSADAI DataService
		 * auth	The name of the OGSADAI resource
		 * 
		 * returns 'true' when successfully connected.
		 */
		bool open(const string& url, const string& auth);
		/**
		 * Close database connection
		 */
		bool close();
		/**
		 * Check if connection is active.
		 * 
		 * returns 'true' if already connected to the database.
		 */
		bool isConnected();
		/**
		 * Send a query statement.
		 * 
		 * Parameters:
		 * sql	The query statement to be passed to the database.
		 * 
		 * returns a string containing the query results encoded in the 
		 * 		   Octave XML format.  
		 */
		string executeQuery(const string& sql);
		/**
		 * Send an update statement. 
		 * Parameters:
		 * sql	The update statement to be passed to the database.
		 * 
		 * returns a string containing the number of modified rows encoded in 
		 * 		   the Octave XML format.
		 */
		string executeUpdate(const string& sql);
	protected:
		/**
		 * Hidden constructor (singleton)
		 */
		OGSADAIConnection();		
	private:
		static OGSADAIConnection* instance;
		bool isconnected;
		JavaVMOption options[1];
	 	JNIEnv *env;
	 	JavaVM *jvm;
	 	JavaVMInitArgs vm_args;
	 	long status;
	 	jclass cls;
	 	jobject obj;
	 	jmethodID mid;
};

#endif /*OGSADAICONNECTION_H_*/
